package deployment

import (
	"context"
	"fmt"
	"k8s.io/api/apps/v1"
	core "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8sapi/lib"
)

func GetLabels(m map[string]string) string {
	labels:=""
	// aa=xxx,xxx=xx
	for k,v:=range m{
		if labels!=""{
			labels+=","
		}
		labels+=fmt.Sprintf("%s=%s",k,v)
	}
	return labels
}

func GetImagesByPod(containers []core.Container) string{
	images:=containers[0].Image
	if imgLen:=len(containers);imgLen>1{
		images+=fmt.Sprintf("+其他%d个镜像",imgLen-1)
	}
	return images
}
//根据deployment获取镜像
func GetImages(dep v1.Deployment) string   {
	return GetImagesByPod(dep.Spec.Template.Spec.Containers)
}
//根据dep 获取 当前rs的标签  --- 给listwatch使用
func GetRsLableByDeployment_ListWatch(dep *v1.Deployment,rslist []*v1.ReplicaSet) ([]map[string]string,error){
	ret:=make([]map[string]string,0)
	for _,item:=range rslist{
		if IsRsByDep(dep,*item){
			s,err:= metav1.LabelSelectorAsMap(item.Spec.Selector)
			if err!=nil{
				return nil,err
			}
			ret=append(ret,s)
			//return ret,nil
		}
	}
	return ret,nil
	//return nil,nil
}
//根据dep 获取 当前rs的标签 ---普通调用API
func GetRsLableByDeployment(dep *v1.Deployment) string{
	selector,_:=  metav1.LabelSelectorAsSelector(dep.Spec.Selector)
	listOpt:=metav1.ListOptions{
		LabelSelector:selector.String(),
	}
	rs,_:=lib.K8sClient.AppsV1().ReplicaSets(dep.Namespace).
		List(context.Background(),listOpt)
	for _,item:=range rs.Items{
		if IsCurrentRsByDep(dep,item){
			s,err:= metav1.LabelSelectorAsSelector(item.Spec.Selector)
			if err!=nil{
				return ""
			}
			return s.String()
		}
	}
	return ""
}
//获取dep的所有RS
func IsRsByDep(dep *v1.Deployment,set v1.ReplicaSet) bool {
	for _,ref:=range set.OwnerReferences{
		if ref.Kind=="Deployment" && ref.Name==dep.Name{
			return true
		}
	}
	return false
}
//通过Dep获取RS(最新的)
func IsCurrentRsByDep(dep *v1.Deployment,set v1.ReplicaSet) bool{
	if set.ObjectMeta.Annotations["deployment.kubernetes.io/revision"]!=dep.ObjectMeta.Annotations["deployment.kubernetes.io/revision"]{
		return false
	}
	return IsRsByDep(dep,set)
}
